package com.stn.zjx.givingtreasure.activity.bi;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.CreateEthDomain;
import com.stn.zjx.givingtreasure.event.CreateImportEthWalletEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshWalletEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.GGTApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.WalletUser;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class CreateEthWalletActivity extends BaseActivity {

    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.tip1)
    TextView tip1;
    @BindView(R.id.tip2)
    TextView tip2;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.confirmpassword_edit)
    EditText confirmpasswordEdit;
    @BindView(R.id.info_tv)
    EditText infoTv;
    @BindView(R.id.agree_cb)
    CheckBox agreeCb;
    @BindView(R.id.service_bt)
    TextView serviceBt;
    @BindView(R.id.create_bt)
    Button createBt;
    @BindView(R.id.import_wallet)
    TextView importWallet;
    @BindView(R.id.rootView)
    LinearLayout rootView;
    @BindView(R.id.password_tip)
    TextView passwordTip;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateImportEth(CreateImportEthWalletEvent event){
        finish();
    }


    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.create_eth_wallet));
        createBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                   if(TextUtils.isEmpty(nameEdit.getText().toString().trim())){
                       showToast(getString(R.string.please_input_wallet_name));
                       return;
                   }
                if(!ToolsUtils.checkName(nameEdit.getText().toString().trim())){
                    showToast(getString(R.string.wallet_name_pattern));
                    return;
                }
                if(TextUtils.isEmpty(passwordEdit.getText().toString().trim())){
                    showToast(getString(R.string.please_inputpassword));
                    return;
                }
                if(!ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())){
                    showToast(getString(R.string.password_validate));
                    return;
                }
                if(TextUtils.isEmpty(confirmpasswordEdit.getText().toString().trim())){
                    showToast(getString(R.string.please_input_repeat_password));
                    return;
                }
                if(!TextUtils.equals(passwordEdit.getText().toString().trim(),confirmpasswordEdit.getText().toString().trim())){
                    showToast(getString(R.string.password_confirm_is_equals));
                    return;
                }

                  createEth(
                          nameEdit.getText().toString().trim(),
                          passwordEdit.getText().toString().trim(),
                          infoTv.getText().toString().trim()
                          );
            }
        });
        createBt.setClickable(false);
        agreeCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    createBt.setBackgroundResource(R.drawable.shape_coloraccent_5dp);
                    createBt.setClickable(true);
                } else {
                    createBt.setBackgroundResource(R.drawable.shape_round_font_lightgray_5dp);
                    createBt.setClickable(false);
                }
            }
        });
        passwordEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                     if(!TextUtils.isEmpty(passwordEdit.getText().toString().trim())){
                           if(ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())){
                              passwordTip.setVisibility(View.GONE);
                           }else{
                               passwordTip.setVisibility(View.VISIBLE);
                           }
                     }
                }
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_eth_wallet);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.service_bt,R.id.import_wallet})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.service_bt:
                bundle.putString("url", GGTApi.service_agreement);
                RxActivityTool.skipActivity(this, GenericWebActivity.class, bundle);
                break;
            case R.id.import_wallet:

                RxActivityTool.skipActivity(this, ImportEthWalletActivity.class, bundle);
                break;
        }
    }

    public void createEth(String walletName,String walletPassword,String tip){

        EthNetImpl
                .create_eth_wallet(walletPassword, "create_eth_wallet", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                         showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    dissmissLoading();
                    }
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            CreateEthDomain domain=new Gson().fromJson(response.body(),CreateEthDomain.class);
                                   switch (domain.getStatus()){
                                       case BaseApi.REQUEST_SUCCESS_CODE:
                                           WalletUser walletUser=new WalletUser();
                                           walletUser.setAddress(domain.getData().getAddress());
                                           walletUser.setMnemonic(domain.getData().getMnemonic());
                                           walletUser.setName(walletName);
                                           walletUser.setPassword(walletPassword);
                                           walletUser.setTradepassword(walletPassword);
                                           walletUser.setPrivate_key("");
                                           walletUser.setTipmessage(tip);
                                           walletUser.setWallet_type(0);
                                           walletUser.setType(0);

                                           if(WalletUserService.getInstance( getApplicationContext())
                                               .save(walletUser)){
                                               Set<String> sets=new HashSet<String>();
                                               String alias_address=domain.getData().getAddress().substring(2,domain.getData().getAddress().length());
                                               sets.add(alias_address+"");
                                               JPushInterface.addTags(getApplicationContext(),1,sets);

                                               if(WalletUserService.getInstance(getApplicationContext())
                                                       .getAddressCount()==1){
                                                   RxActivityTool.skipActivity(getApplicationContext(),BiMainActivity.class);
                                               }
                                               Bundle bundle=new Bundle();
                                               bundle.putString("address",domain.getData().getAddress());
                                               RxActivityTool.skipActivity(CreateEthWalletActivity.this,FirstCreateEthBackUpActivity.class,bundle);

                                               RefreshWalletEvent refreshWalletEvent=new RefreshWalletEvent();
                                                refreshWalletEvent.flag=RefreshWalletEvent.INITREFRESH;
                                               EventBus.getDefault().post(refreshWalletEvent);

                                               CreateImportEthWalletEvent event=new CreateImportEthWalletEvent();
                                               EventBus.getDefault().post(event);



                                           }else{
                                               showToast(getString(R.string.db_error));
                                           }
                                           break;
                                     default:
                                         showToast(domain.getMessage());
                                         break;
                                   }
                        }

                    }
                });
    }
}
